//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

namespace Provenance
{
    using System;
    using System.Windows;
    using System.Windows.Controls;
    using Microsoft.Research.Provenance.Controls;
    using Microsoft.Research.Provenance.ProvenanceDataService;
    using Microsoft.Research.ProvenanceInterfaces;
    using Microsoft.Research.ScientificWorkflow.TridentUtilities;
    using Microsoft.Practices.Unity;
    using Microsoft.Research.DataLayer;
    using SR = Microsoft.Research.DataLayer;
    using System.Globalization;
    using Microsoft.Research.ScientificWorkflow.UIDesigner;
    using Microsoft.Research.ScientificWorkflow.TridentComposer;
    using Microsoft.Research.ScientificWorkflow.TridentModel;
    using System.Collections.Generic;

    /// <summary>
    /// Interaction logic for ProvenanceWindow.xaml
    /// </summary>
    public sealed partial class ProvenanceWindow : Window, IDisposable
    {
        /// <summary>
        /// Constructor
        /// </summary>
        public ProvenanceWindow()
        {
            InitializeComponent();

            this.ReadDatatypes();

            // Initialize icon for data products.
            try
            {
                DataProductIconBuilder.Initialize();
                DataProductIconBuilder.ExtractIcons();
            }
            catch (TridentCustomException ex)
            {
                TridentErrorHandler.HandleUIException(ex);
            }
        }

        /// <summary>
        /// Sets the Title for the Provenancewindow
        /// </summary>
        public string ProvenanceTitle
        {
            get
            {
                return this.Title;
            }
            set
            {
                this.Title = value;
            }
        }

        /// <summary>
        /// Holds an instance of the current job id.
        /// </summary>
        private Guid currentJobID = Guid.Empty;

        /// <summary>
        /// The datatypes info dictionary. Contains the color codes and the names of the recognized datatypes.
        /// </summary>
        private Dictionary<String, DataTypeModel> dataTypes = new Dictionary<string, DataTypeModel>();

        /// <summary>
        /// Holds an instance of current provenance control.
        /// </summary>
        private ProvenanceControl provenanceControl;

        /// <summary>
        /// Event handler for Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnWindowLoaded(object sender, RoutedEventArgs e)
        {
            this.ReadConsoleParameters();

            if (this.currentJobID != null && !this.currentJobID.Equals(Guid.Empty))
            {
                this.LoadProvenanceInformation();

                this.SetTitle();
            }
        }

        /// <summary>
        /// Read the console parameters passed as command line parameter.
        /// </summary>
        private void ReadConsoleParameters()
        {
            try
            {
                if (Application.Current.Properties.Contains("JobID"))
                {
                    string jobToOpen = (string)Application.Current.Properties["JobID"];

                    this.currentJobID = new Guid(jobToOpen);
                }
            }
            catch (FormatException exp)
            {
                TridentMessageBox.ShowTridentErrorMessageBox(exp.Message);
            }
            catch (OverflowException exp)
            {
                TridentMessageBox.ShowTridentErrorMessageBox(exp.Message);
            }
        }

        /// <summary>
        /// Loads the provenance control.
        /// </summary>
        private void LoadProvenanceInformation()
        {
            try
            {
                this.provenanceControl = new ProvenanceControl(this.currentJobID, this.dataTypes);
                this.provenanceControlHost.Children.Add(this.provenanceControl);
            }
            catch (TridentCustomException exp)
            {
                TridentMessageBox.ShowTridentErrorMessageBox(exp.Message);
                Environment.Exit(0);
            }
            catch (Exception exp)
            {
                TridentErrorHandler.HandleUIException(exp);
                TridentMessageBox.ShowTridentErrorMessageBox(exp.Message);
                Environment.Exit(0);
            }
        }

        /// <summary>
        /// Sets the title of the provenance windows.
        /// </summary>
        private void SetTitle()
        {
            string provenanceMessage = ProvenanceResourceManager.GetString("ProvenanceWindowTitleString");

            // Set the title of the provenance window to the job name.
            this.ProvenanceTitle = string.IsNullOrEmpty(provenanceControl.JobName) ?
                provenanceMessage :
                string.Format(CultureInfo.InvariantCulture, "{0} - {1}", provenanceControl.JobName, provenanceMessage);
        }


        /// <summary>
        /// Read the datatypes.
        /// </summary>
        private void ReadDatatypes()
        {
            DataTypesComposer.ReadAllDataTypes(this.dataTypes);
            UIHelper.ReadUserDataTypeXml(this.dataTypes);
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (this.provenanceControl != null)
                this.provenanceControl.Dispose();

            GC.SuppressFinalize(this);
        }

        #endregion
    }
}
